<template>
  <div class="container">
    <!-- 导航固定定位 fixed -->
    <van-nav-bar
      fixed
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 文章列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      finished-text="没有更多了"
    >
      <van-cell
        :to="`/article/${item.art_id.toString()}`"
        v-for="item in list"
        :key="item.art_id.toString()"
      >
        <div class="article_item">
          <h3 class="van-ellipsis">
            {{ item.title }}
          </h3>
          <div class="img_box" v-if="item.cover.images.length">
            <van-image
              v-for="(img, i) in item.cover.images"
              :key="i"
              :class="item.cover.type === 1 ? 'w100' : 'w33'"
              fit="cover"
              :src="img"
            />
          </div>
          <div class="info_box">
            <span>{{ item.aut_name }}</span>
            <span>{{ item.comm_count }}评论</span>
            <span>{{ item.pubdate | relTime }}</span>
          </div>
        </div>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { searchArticles } from '@/api/article'
export default {
  name: 'search-result',
  data () {
    return {
      // 搜索结果列表
      list: [],
      // 列表加载状态
      loading: false,
      // 列表是否加载完成
      finished: false
    }
  },
  created () {
    // 初始化分页查询数据=》存储到组件实例this上
    this.query = {
      page: 1,
      q: this.$route.query.q
    }
    console.log(this)
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const { status, data } = await searchArticles(this.query)
      if (status === 200) {
        // 修改列表数据=>追加
        this.list.push(...data.results)
        // 加载状态结束
        this.loading = false

        // 数据全部加载完成
        if (this.list.length === data.total_count) {
          this.finished = true
        } else {
          // 获取下一页数据=》分页数据加1
          this.query.page++
        }
      }
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding-top: 46px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}
.article_item {
  h3 {
    font-weight: normal;
    line-height: 2;
  }
  .img_box {
    display: flex;
    justify-content: space-between;
    .w33 {
      width: 33%;
      height: 90px;
    }
    .w100 {
      height: 180px;
      width: 100%;
    }
  }
  .info_box {
    color: #999;
    line-height: 2;
    position: relative;
    span {
      padding-right: 10px;
    }
  }
}
</style>
